package com.artezio.testapp.dao;

import java.util.List;


import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.artezio.testapp.domain.City;
import com.artezio.testapp.domain.Person;

@Repository
public class PersonDAOImpl implements PersonDAO {
	
	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);

	@Autowired
	private SessionFactory sessionFactory;

	public void addPerson(Person person) {
		sessionFactory
			.getCurrentSession()
			.saveOrUpdate(person);
	}
	
	public Person getPerson(Integer id) {
		
		return (Person)sessionFactory
				.getCurrentSession()
				.createCriteria(Person.class)
				.add(Restrictions.idEq(id))
				.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<Person> listPerson() {
		
		return sessionFactory
				.getCurrentSession()
				.createCriteria(Person.class)
				.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Person> listPerson(String name, City city, Boolean philosopher){
		
		Criteria criteria =	sessionFactory.getCurrentSession().createCriteria(Person.class);
		
		if(name!=null && name.length()>0){
			criteria = criteria.add(Restrictions.like("name", "%"+name+"%"));
		}
		
		if(city!=null && city.getId()!=null){
			criteria = criteria.add(Restrictions.eq("city", city));
		}
		
		if(philosopher!=null && philosopher){
			criteria = criteria.add(Restrictions.eq("philosopher", philosopher));
		}
		
		return criteria.list();
	}

	public void removePerson(Integer id) {
		Person person = (Person) sessionFactory
				.getCurrentSession()
				.load(Person.class, id);
		if (null != person) {
			sessionFactory.getCurrentSession().delete(person);
		}

	}
}
